const Webpack = require("webpack");
const friendlyErrorsWebpackPlugin = require("friendly-errors-webpack-plugin");
const { resolve } = require("./config/util");
const config = require("./config/webpack.env.base");

const port = 8080;

// 以VUE_APP开头的环境变量注入到process.env中
function configWebpackEnvironment() {
  const envVar = {};
  for (const key in process.env) {
    if (key.startsWith("VUE_APP")) {
      envVar[key] = process.env[key];
    }
  }
  config.plugins.push(new Webpack.EnvironmentPlugin(envVar));
}

function configWebpackDevServer() {
  config.devServer = {
    port,
    client: {
      overlay: {
        errors: true,
        warnings: false,
      },
    },
    proxy: {
      [process.env.VUE_APP_BASE_API]: {
        target: process.env.VUE_APP_SERVER_ADDRESS,
        changeOrigin: true, // needed for virtual hosted sites
        // ws: true, // proxy websockets
        pathRewrite: {
          ["^" + process.env.VUE_APP_BASE_API]: "",
        },
      },
    },
  };
}

function configWebpackServePlugins() {
  config.plugins.push(
    //命令行友好提示
    new friendlyErrorsWebpackPlugin({
      compilationSuccessInfo: {
        messages: [`You application is running here http://localhost:${port}`],
        notes: [
          "Some additional notes to be displayed upon successful compilation",
        ],
      },
      onErrors: function (severity, errors) {},
      clearConsole: true,
      additionalFormatters: [],
      additionalTransformers: [],
    })
  );
}

function configWebpackOutput() {
  config.output = {
    path: resolve("../build"),
    pathinfo: false, // 设置为false可以提升编译性能
    publicPath: "./",
    clean: true,
    assetModuleFilename: "assets/[name]-[hash][ext]",
    filename: "js/[name]-[fullhash].js",
  };
}

function configWebpackOptimization() {
  config.optimization = {
    splitChunks: {
      cacheGroups: {
        commons: {
          name: "commons",
          chunks: "initial",
          minChunks: 2,
        },
      },
    },
    runtimeChunk: true,
  };
}

module.exports = (env) => {
  const mode = env.mode;

  // 向node实例注入环境变量
  require("dotenv").config({
    path: `./config/.env.${mode}`,
  });

  const isProp = process.env.NODE_ENV === "production";
  config.mode = process.env.NODE_ENV;

  config.entry = resolve('../src/main.js');

  configWebpackEnvironment();

  if (!isProp) {
    config.devtool = "eval-cheap-module-source-map";
  }

  // https://webpack.js.org/api/cli/#build
  // 如果是执行的webpack serve命令而不是webpack build命令
  if (env.WEBPACK_SERVE) {
    configWebpackDevServer();
    configWebpackServePlugins();
  } else {
    configWebpackOutput();
    configWebpackOptimization();
  }
  return config;
};
